package com.qyhl.webtv.module_circle.circle.userlist.fragment;

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.qyhl.webtv.basiclib.utils.glide.GlideCircleTransform;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.ViewPageFragment;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/2/8.
 */

public class UserListFragment extends ViewPageFragment implements UserListContract.UserListView {

    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    private View view;
    /**
     * 数据是否第一次加载
     */
    private boolean mIsInited;
    /**
     * 布局界面初始化
     */
    private boolean mIsPrepared;

    private int type;//1 关注  2 粉丝

    private UserListPresenter mPresenter;

    private List<CircleHomeBean.User> mDataList;

    private CommonAdapter commonAdapter;

    private EmptyWrapper emptyWrapper;

    public void setType(int type) {
        this.type = type;
    }

    @Nullable
    @Override
    public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.circle_fragment_user_list, null);
        ButterKnife.bind(this, view);
        mIsPrepared = true;
        return view;
    }

    public static UserListFragment newInstance(int type) {
        UserListFragment fragment = new UserListFragment();
        fragment.setType(type);
        return fragment;
    }

    /**
     * 加载数据
     */
    private void loadData() {
        mIsInited = true;
        //下拉刷新
        if (type == 1) {
            mPresenter.getFollow();
        } else {
            mPresenter.getFans();
        }
    }

    /**
     * 懒加载数据
     */
    public void lazyLoad() {
        if (getUserVisibleHint() && mIsPrepared && !mIsInited) {
            //异步初始化，在初始化后显示正常UI
            loadData();
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            lazyLoad();
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter = new UserListPresenter(this);
        initView();
        setListener();
        lazyLoad();
    }

    /**
     * 初始化
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        mDataList = new ArrayList<>();

        refresh.setEnableLoadMore(false);
        refresh.setRefreshHeader(new MaterialHeader(getContext()));

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        //添加自定义分割线
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getContext(), R.drawable.circle_recycleview_divider2));
        recyclerView.addItemDecoration(divider);

        commonAdapter = new CommonAdapter<CircleHomeBean.User>(getContext(), R.layout.circle_item_user_list, mDataList) {

            @Override
            protected void convert(ViewHolder holder, final CircleHomeBean.User user, final int position) {
                ImageView headIcon = holder.getView(R.id.head_icon);
                Glide.with(getContext())
                        .load(user.getLogo())
                        .apply(new RequestOptions().error(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default).transform(new GlideCircleTransform(getContext())))
                        .into(headIcon);

                TextView nickName = holder.getView(R.id.nickName);
                nickName.setText(user.getNickName());

                final ImageView follow = holder.getView(R.id.follow_btn);
                if (type == 1) {
                    if (user.isBoth()) {
                        follow.setVisibility(View.VISIBLE);
                        follow.setImageResource(R.drawable.circle_follow_both);
                    } else {
                        follow.setVisibility(View.VISIBLE);
                        follow.setImageResource(R.drawable.circle_follow_on);
                    }
                } else {
                    if (user.isBoth()) {
                        follow.setVisibility(View.VISIBLE);
                        follow.setImageResource(R.drawable.circle_follow_both);
                    } else {
                        follow.setVisibility(View.VISIBLE);
                        follow.setImageResource(R.drawable.circle_follow_off);
                    }
                }

                follow.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (follow.getDrawable().getCurrent().getConstantState().equals(ContextCompat.getDrawable(getContext(), R.drawable.circle_follow_off).getConstantState())) {
                            mPresenter.doFollow(user.getUsername(), follow, position);
                        } else {
                            mPresenter.undoFollow(user.getUsername(), follow, position);
                        }
                    }
                });

            }
        };

        emptyWrapper = new EmptyWrapper(commonAdapter);
        if (type == 2) {
            View view = LayoutInflater.from(getContext()).inflate(R.layout.circle_layout_circleuser_emptyview, recyclerView, false);
            TextView text = view.findViewById(R.id.empty_text);
            text.setText("暂无内容");
            ImageView img = view.findViewById(R.id.empty_img);
            img.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.empty_content));
            emptyWrapper.setEmptyView(view);
        }else {
            emptyWrapper.setEmptyView(R.layout.circle_layout_circleuser_emptyview);
        }
        recyclerView.setAdapter(emptyWrapper);


    }

    /**
     * 设置监听
     */
    private void setListener() {
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                if (type == 1) {
                    mPresenter.getFollow();
                } else {
                    mPresenter.getFans();
                }
            }
        });

        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                if (type == 1) {
                    mPresenter.getFollow();
                } else {
                    mPresenter.getFans();
                }
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("dstusername", mDataList.get(position).getUsername());
                RouterManager.router(ARouterPathConstant.CIRCLE_USER,bundle);

            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    /**
     * 设置数据
     *
     * @param beanList
     */
    @Override
    public void setDatas(List<CircleHomeBean.User> beanList) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");

        mDataList.clear();
        mDataList.addAll(beanList);

        emptyWrapper.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void setNetError(String msg) {
        refresh.finishRefresh();
        loadMask.setStatus(LoadingLayout.No_Network);
        loadMask.setNoNetworkText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    @Override
    public void followSuccess(String msg, ImageView follow, int position) {
        Toasty.normal(getContext(), msg).show();
        if (type == 1) {
            follow.setImageResource(R.drawable.circle_follow_on);
        } else {
            follow.setImageResource(R.drawable.circle_follow_both);
        }

        mDataList.get(position).setFollow(true);
        BusFactory.getBus().post(new Event.followNumRefresh());
    }

    @Override
    public void followError(String msg) {
        Toasty.normal(getContext(), msg).show();
    }

    @Override
    public void unFollowSuccess(String msg, ImageView follow, int position) {
        Toasty.normal(getContext(), msg).show();
        if (type == 1) {
            mPresenter.getFollow();
        } else {
            mPresenter.getFans();
        }
        BusFactory.getBus().post(new Event.followNumRefresh());

    }

    @Override
    public void unFollowError(String msg) {
        Toasty.normal(getContext(), msg).show();
    }
}
